package com.ftg.learn.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author: huye
 * @Description: TODO
 * @DateTime: 2022/3/14 8:40
 **/
public class BaseController <E,T extends IService<E>> {
    @Autowired(required = false)
    public T service;

    @GetMapping("/showAll")
    public ResEntity showAll(){
        return new ResEntity(0,"success",service.list());
    }




    @GetMapping("/page")
    public ReturnData<E> page(int page , int limit, HttpServletRequest request){

        //获得当前请求里面所有参数 page=1 limit =10 uaccunt=a
        Map<String, String[]> map = request.getParameterMap();
        Set<Map.Entry<String, String[]>> keys = map.entrySet();

        IPage<E> ip =new Page<>(page,limit);
        QueryWrapper<E> qw = null;
        for(Map.Entry<String, String[]> e:keys){
            if(!e.getKey().equals("page") && !e.getKey().equals("limit")
                    && e.getValue().length > 0 && !e.getValue()[0].equals("")){
                qw = (qw == null ? new QueryWrapper<>():qw);
                qw.like(e.getKey(),e.getValue()[0]);
            }
        }
        service.page(ip,qw);

        ReturnData returnData = new ReturnData();
        returnData.setData(ip.getRecords());
        returnData.setPage(page);
        returnData.setLimit(limit);
        returnData.setCount(ip.getTotal());
        returnData.setCode(0);
        returnData.setMsg("success");

        return returnData;
    }
    @PostMapping("/saveOrUpdte")
    //RequestBody 一会你看到swagger 理解，表示你传递给我的参数 E e {id:123,name:'kjx'}
    public boolean saveEntity(@RequestBody E e){
        return service.saveOrUpdate(e);
    }

    /**
     * 这个添加方法  是不是要求有参数 E 前面有一个注解requestbody 修饰的时候，这个参数要的是json格式
     * @param e
     * @return
     */
    @PostMapping("/save")
    public boolean save(@RequestBody E e){
        return service.save(e);
    }

    @PutMapping("/update")
    public boolean update(@RequestBody E e){
        return service.updateById(e);
    }

    //  "/del/123"
    @DeleteMapping("/del/{id}")
    public boolean deleteE(@PathVariable("id") Serializable id){
        return service.removeById(id);
    }

    @PostMapping("/dels")
    public boolean deletes(@RequestBody List<Serializable> ids){
        System.out.println(ids.get(0));
        return service.removeBatchByIds(ids);
    }
}
